<?php

namespace App\Http\Controllers\Api;

use App\ActiveParty;
use App\ActivePartyBanner;
use App\Activity;
use App\ActivityBindGoods;
use App\ActivityBrowseRecord;
use App\ActivityImg;
use App\Classify;
use App\Exceptions\SecurityException;
use App\Files;
use App\Goods;
use App\Http\Services\FileManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\IntegralChildRule;
use App\IntegralRule;
use App\InvitationCard;
use App\JoinActivity;
use App\Services\UserManager;
use App\User;
use App\UserActivity;
use App\UserActivityGuest;
use App\UserCollection;
use App\UserInfo;
use App\UserIntegralRecord;
use App\UserPayment;
use App\UserVip;
use App\VipInfo;
use Illuminate\Support\Facades\Input;
use Intervention\Image\Facades\Image;
use App\Http\Requests\BespokeRequest;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class ActivityController extends Controller
{
//    /**
//     *获取活动分类
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function activityClassify(Request $request){
//
//        $classifies=Classify::wherePid(0)->whereType('activity')->orderBy('sort','asc')->orderBy('created_at','desc')->get();
//        if(count($classifies)>0){
//            foreach($classifies as $classify){
//                $classify->img_url=FileManager::getImgUrl($classify->img_id);
//
//                $classifyChild = Classify::wherePid($classify->id)->whereType('activity')->count();
//                if($classifyChild > 0){
//                    $classify->has_secondary = 1;
//                }else{
//                    $classify->has_secondary = 0;
//                }
//
//                /** @var Classify $classifyChild */
//                $classifyChildList = Classify::wherePid($classify->id)->whereType('activity')->get();
//                $classify->child_classify_list = $classifyChildList;
//            }
//        }
//
//        return response()->json(["level"=>"success","message"=>"获取成功！","data"=>$classifies]);
//    }

    /**
     * 获取活动列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivity(Guard $guard,Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);

        $keywords      = Input::get('keywords');
        $classifyId    =  Input::get('classify_id');
        $activePartyId = !is_null( Input::get('active_party_id')) ?  Input::get('active_party_id') : 0;
        $limit         = !is_null( Input::get('limit')) ?  Input::get('limit') : 8;
        $page          = !is_null( Input::get('page')) ?  Input::get('page') : 0;
        $choice        = !is_null( Input::get('choice')) ?  Input::get('choice') : 0;
        $province      = !is_null( Input::get('province')) ?  Input::get('province') : "";
        $city          = !is_null( Input::get('city')) ?  Input::get('city') : "";
        $area          = !is_null( Input::get('area')) ?  Input::get('area') : "";
        $todayY        = !is_null( Input::get('today_y')) ?  Input::get('today_y') : "";
        $todayM        = !is_null( Input::get('today_m')) ?  Input::get('today_m') : "";
        $todayD        = !is_null( Input::get('today_d')) ?  Input::get('today_d') : "";

        $activities = DB::table('activity')->whereNull('deleted_at');

        if(!is_null($classifyId)&& $classifyId!=0 && $classifyId!=""){
            $activities = $activities->whereClassifyId($classifyId);
        }

        if($activePartyId != 0 && $activePartyId != ''){
            $activities = $activities->whereActivePartyId($activePartyId);
        }

        if(!is_null($keywords) && $keywords!=""){
            $activities = $activities->where('name','like',"%".$keywords."%");
        }

        if($province != ""){
            $activities = $activities->where("province","like","%".$province."%");
        }

        if($city != ""){
            $activities = $activities->where("city","like","%".$city."%");
        }

        if($area != ""){
            $activities = $activities->where("area","like","%".$area."%");
        }

        if($todayY != "" && $todayM != "" && $todayD != ""){
            $firstToday = mktime(0,0,0,$todayM,$todayD,$todayY);
            $lastToday  = mktime(23,59,59,$todayM,$todayD,$todayY);

            $firstDateToday = date("Y-m-d H:i:s",$firstToday);
            $endDateToday   = date("Y-m-d H:i:s",$lastToday);

            $activities = $activities->whereBetween('start_time',[$firstDateToday,$endDateToday]);
        }

        if($choice !='' && $choice != 0){
            $activities = $activities->whereStatus(1)->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }else{
            $activities = $activities->whereStatus(1)->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }

        if(count($activities)){
            foreach($activities as $activity){
                $activity->img_url = route('Api.Image.Show',['id' => $activity->img_id]);
                $activity->week    = date("W",strtotime($activity->start_time));

                if($user){
                    /** @var UserActivity $thisJoinActivity */
                    $thisJoinActivity = UserActivity::whereUserId($user->id)->whereActivityId($activity->id)->whereStatus(1)->first();
                    if($thisJoinActivity){
                        $activity->is_join = 1;
                    }else{
                        $activity->is_join = 2;
                    }
                }else{
                    $activity->is_join       = null;
                }

                $userActivity = UserActivity::whereActivityId($activity->id)->whereStatus(1)->count();

                $activity->join_num = $userActivity;

//                $activityBrowseNum = ActivityBrowseRecord::whereActivityId($activity->id)->count();
//                $activity->browse_num = $activityBrowseNum;

//                /** @var Classify $classify */
//                $classify = Classify::whereType('activity')->whereId($activity->classify_id)->first();
//                if($classify){
//                    $classify->img_url = FileManager::getImgUrl($classify->img_id);
//
//                    $activity->classify_info = $classify;
//                }else{
//                    $activity->classify_info = null;
//                }
            }
        }

        return response()->json(["level"=>"success","message" => "获取成功！","activities" => $activities]);
    }

    /**
     * 获取活动详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivityDetail(Guard $guard,Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);

        $activityId = !is_null( Input::get('activity_id')) ?  Input::get('activity_id') : 0;

        /** @var Activity $activityDetail */
        $activityDetail = Activity::whereId($activityId)->whereStatus(1)->first();
        if($activityDetail){
            $activityDetail->img_url   = route('Api.Image.Show',['id' => $activityDetail->img_id]);
//            $activityDetail->video_url = FileManager::getVideoUrl($activityDetail->video_id);
            $activityDetail->week    = date("W",strtotime($activityDetail->start_time));
//            if($activityDetail->type == 'pc'){
//                $activityDetail->detail     = str_replace('/uploads/ueditor/php/upload/image/',env('HOST_URL').'/uploads/ueditor/php/upload/image/',$activityDetail->detail);
////                $activityDetail->app_detail = null;
//            }else{
//                $activityDetail->detail = null;
//            }

//            $activityBrowseNum = ActivityBrowseRecord::whereActivityId($activityDetail->id)->count();
//            $activityDetail->browse_num = $activityBrowseNum;

            $activityDetail->detail     = str_replace('/uploads/ueditor/php/upload/image/',env('HOST_URL').'/uploads/ueditor/php/upload/image/',$activityDetail->detail);

            if($user){
                /** @var UserActivity $thisJoinActivity */
                $thisJoinActivity = UserActivity::whereUserId($user->id)->whereActivityId($activityDetail->id)->whereIn('status',[1,2])->first();
                if($thisJoinActivity){
                    $activityDetail->is_join = 1;
                    if(!is_null($thisJoinActivity->seat_num) && $thisJoinActivity->seat_num != ''){
                        $activityDetail->seat_num = $thisJoinActivity->seat_num;
                    }else{
                        $activityDetail->seat_num = '';
                    }
                }else{
                    $activityDetail->is_join = 2;
                    $activityDetail->seat_num = '';
                }
            }else{
                $activityDetail->is_join       = null;
                $activityDetail->seat_num = '';
            }

            /** @var UserActivity $userActivity */
            $userActivityList = UserActivity::whereActivityId($activityDetail->id)->whereStatus(1)->get();
            $joinNumArr = array();
            if(count($userActivityList) > 0){
                foreach($userActivityList as $userActivity){

                    /** @var UserInfo $userInfo */
                    $userInfo = UserInfo::whereUserId($userActivity->user_id)->first();
                    if($userInfo){
                        $userInfo->photo_url = route('Api.Image.Show',['id' => $userInfo->portrait_id]);
                    }else{
                        $userInfo->photo_url = null;
                    }

                    array_push($joinNumArr,$userInfo);
                }
            }

            $activityDetail->join_user_list = $joinNumArr;

            $userActivity = UserActivity::whereActivityId($activityDetail->id)->whereStatus(1)->count();

            $activityDetail->join_num = $userActivity;

            $activityDetail->mingyi_qr_code_img_url = url('images/wechat.jpg');

//            $activityBrowseNum = ActivityBrowseRecord::whereActivityId($activityDetail->id)->count();
//            $activityDetail->browse_num = $activityBrowseNum;

//            if($activityDetail->show_goods == 1){
//                /** @var ActivityBindGoods $activityBindGoods */
//                $activityBindGoodsList = ActivityBindGoods::whereActivityId($activityDetail->id)->get();
//                $goodsList = array();
//                if(count($activityBindGoodsList) > 0){
//                    foreach($activityBindGoodsList as $activityBindGoods){
//                        /** @var Goods $thisGoods */
//                        $thisGoods = Goods::whereId($activityBindGoods->goods_id)->whereIsShop(1)->first();
//                        if($thisGoods){
//                            $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
//                        }
//
//                        array_push($goodsList,$thisGoods);
//                    }
//                }
//
//                $activityDetail->goods_list = $goodsList;
//            }else{
//                $activityDetail->goods_list = null;
//            }

//            if($activityDetail->show_advert == 1){
//                $activityDetail->advert_img_url = FileManager::getImgUrl($activityDetail->advert_img_id);
//            }else{
//                $activityDetail->advert_img_url = null;
//            }

//            if($activityDetail->type == 'app'){
//                /** @var ActivityImg $activityInfoImg */
//                $activityInfoImgList = ActivityImg::whereActivityId($activityDetail->id)->get();
//                $activityInfoImgUrlArr = array();
//                if(count($activityInfoImgList) > 0){
//                    foreach($activityInfoImgList as $activityInfoImg){
//                        $activityInfoImgUrl = FileManager::getImgUrl($activityInfoImg->img_id);
//                        array_push($activityInfoImgUrlArr,$activityInfoImgUrl);
//                    }
//                }
//
//                $activityDetail->activity_info_img_list = $activityInfoImgUrlArr;
//            }else{
//                $activityDetail->activity_info_img_list = [];
//            }

            if(strtotime($activityDetail->end_time) > time()){
                $activityDetail->review = null;
            }


        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activityDetail]);
    }

    /**
     * 获取分享二维码图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\WechatException
     */
    public function generateShareQrCode(Guard $guard){
        /** @var User $user */
        if ($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $user = $guard->user();

        $activityId = !is_null( Input::get('activity_id')) ?  Input::get('activity_id') : 0;

        /** @var Activity $thisActivity */
        $thisActivity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$thisActivity)
            return response()->json(['level' => 'error','message' => '活动已下架']);

        if($thisActivity->share_img_id != 0){
            $url = FileManager::getImgUrl($thisActivity->share_img_id);
            return response()->json(['level' => 'success','message' => '获取成功','data' => $url]);
        }

        if($thisActivity->qr_code_img_id == 0){
            $scene = "id=".$thisActivity->id;
            $path  = 'pages/detail/main?'.$scene;

            //生成微信小程序的二维码图片
            $wxAppQrCodeContent = WechatLogin::getWxUnlimitQrcodeByToken($path);
            if($wxAppQrCodeContent){
                $filoInfo = FileManager::saveFileByFileContent($wxAppQrCodeContent,"qr_code_" . $thisActivity->id . ".jpg","");
                $newImage = new Images();
                $newImage->file_id          = $filoInfo->id;
                $newImage->img_name         = "qr_code_" . $thisActivity->id . ".jpg";
                $newImage->img_type         = $filoInfo->file_type;
                $newImage->save();

                $thisActivity->qr_code_img_id = $newImage->id;
                $thisActivity->save();
            }else{
                return response()->json(['level' => 'error','message' => '二维码生成失败,请联系客服']);
            }
        }else{
            /** @var Images $qrCodeImg */
            $qrCodeImg = Images::whereId($thisActivity->qr_code_img_id)->first();
            if(!$qrCodeImg)
                return false;

            /** @var Files $qrCodeFile */
            $qrCodeFile = Files::whereId($qrCodeImg->file_id)->first();
            if(!$qrCodeFile)
                return false;

            $wxAppQrCodeContent = $qrCodeFile->getContent();
        }

        //背景图片
        $backgroundImgInfo = Image::make(url('images/fenxiang.png'));

        //二维吗图片
        $wxAppQrCodeImgInfo = Image::make($wxAppQrCodeContent);

        //设置二维吗图片的的大小
        $wxAppQrCodeImgInfo->resize(250,250);
        //调整二维吗在背景图片上的位置
        $backgroundImgInfo->insert($wxAppQrCodeImgInfo,'top-left',175,380);

        if($thisActivity->img_id != 0){
            /** @var Images $thisImg */
            $thisImg = Images::whereId($thisActivity->img_id)->first();
            if(!$thisImg)
                $activityImgContent = url('images/default_img.png');

            /** @var Files $thisFile */
            $thisFile = Files::whereId($thisImg->file_id)->first();
            if(!$thisFile)
                $activityImgContent = url('images/default_img.png');

            $activityImgContent = $thisFile->getContent();
        }else{
            $activityImgContent = url('images/default_img.png');
        }

        //活动图片
        $activityImgInfo = Image::make($activityImgContent)->resize(520,320);;

        //调整活动图片在背景图片上的位置
        $backgroundImgInfo->insert($activityImgInfo,'top-left',40,20);

        //拼写地址信息
        $activityAddressInfo = mb_strimwidth($thisActivity->province . $thisActivity->city . $thisActivity->area . $thisActivity->address_detail,0,44,'...','utf-8');

        //调整地址信息在图片上的位置
        $backgroundImgInfo->text($activityAddressInfo, 160, 700, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(14);
            $font->color('#000000');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        //活动主题
        $activityThemeInfo = mb_strimwidth($thisActivity->theme,0,20,'...','utf-8');

        //调整活动主题在图片上的位置
        $backgroundImgInfo->text($activityThemeInfo, 220, 670, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(18);
            $font->color('#000000');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        //活动时间
        $activityTimeInfo = $thisActivity->start_time;

        //调整活动时间在图片上的位置
        $backgroundImgInfo->text($activityTimeInfo, 220, 730, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(14);
            $font->color('#000000');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        //输出图片
        $response = response()->make($backgroundImgInfo->encode('jpg'));
        $response->header('Content-Type', 'image/jpg');

        return $response;
    }

    /**
     * 活动浏览量记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function activityBrowseRecord(Guard $guard){
        if ($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $user = $guard->user();

        $activityId = !is_null( Input::get('activity_id')) ?  Input::get('activity_id') : 0;

        /** @var Activity $activity */
        $activity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$activity)
            return response()->json(['level' => 'error','message' => '该活动不存在']);

        $thisActivityBrowseRecord = ActivityBrowseRecord::whereActivityId($activity->id)->whereUserId($user->id)->first();
        if(!$thisActivityBrowseRecord){
            $thisActivityBrowseRecord = new ActivityBrowseRecord();
            $thisActivityBrowseRecord->user_id       = $user->id;
            $thisActivityBrowseRecord->activity_id   = $activity->id;
            $thisActivityBrowseRecord->save();
        }

        return response()->json(['level' => 'success','message' => '记录成功','data' => $thisActivityBrowseRecord]);
    }

    /**
     * 获取活动状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function activityCheckStatus(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $activityId = !is_null( Input::get('activity_id')) ?  Input::get('activity_id') : 0;

        /** @var Activity $thisActivity */
        $thisActivity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$thisActivity)
            return response()->json(['level' => 'error','message' => '会议不存在']);

        if(strtotime($thisActivity->end_time) <= time())
            return response()->json(['level' => 'error','message' => '会议已结束']);

        /** @var UserActivity $userActivity */
        $userActivity = UserActivity::whereUserId($user->id)->whereActivityId($thisActivity->id)->whereStatus(1)->first();
        if(!$userActivity)
            return response()->json(['level' => 'error','message' => '您还没有参与该会议']);

        if($userActivity->is_sign == 1){
            $status = 1;
        }else{
            $status = 0;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $status]);
    }

    /**
     * 活动签到接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function activityCheckIn(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if (!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $activityId = !is_null( Input::get('activity_id')) ?  Input::get('activity_id') : 0;

        /** @var Activity $thisActivity */
        $thisActivity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$thisActivity)
            return response()->json(['level' => 'error','message' => '会议不存在']);

        if(strtotime($thisActivity->end_time) <= time())
            return response()->json(['level' => 'error','message' => '会议已结束']);

        /** @var UserActivity $userActivity */
        $userActivity = UserActivity::whereUserId($user->id)->whereActivityId($thisActivity->id)->whereStatus(1)->first();
        if(!$userActivity)
            return response()->json(['level' => 'error','message' => '没有参加会议','data' => 'no_join']);

        if(strtotime($thisActivity->start_time) > time())
            return response()->json(['level' => 'error','message' => '会议还未开始']);

        if($userActivity->is_sign == 1)
            return response()->json(['level' => 'error','message' => '您已经签到过了']);

        $userActivity->is_sign = 1;
        $userActivity->save();

        return response()->json(['level' => 'success','message' => '签到成功','data' => $userActivity]);
    }

    /**
     * 线下报名支付
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function activitySignUpOffline(Guard $guard){
        if ($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        $user = $guard->user();

        $activityId =  Input::get("activity_id");
        $realName   =  Input::get('real_name');
        $phone      =  Input::get('phone');
        $wechat     =  Input::get('wechat');
        $isGuest    = !is_null( Input::get('is_guest')) ?  Input::get('is_guest') : 0;
        $guestInfo  =  Input::get('guest_info');

        /** @var Activity $thisActivity */
        $thisActivity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$thisActivity)
            return response()->json(['level' => 'error','message' => '活动已下架']);

        if(strtotime($thisActivity->start_time) <= time())
            return response()->json(['level' => 'error','message' => '报名已停止']);

        if(strtotime($thisActivity->end_time) <= time())
            return response()->json(['level' => 'error','message' => '活动已结束']);

        /** @var VipInfo $isVipUser */
        $isVipUser = VipInfo::whereUserId($user->id)->whereIsVip(1)->whereStatus(1)->first();
        if(!$isVipUser)
            return response()->json(['level' => 'error','message' => '您不是会员，不能参与该活动']);

        if(strtotime($isVipUser->end_time) <= time())
            return response()->json(['level' => 'error','message' => '您的会员已过期']);

        /** @var UserActivity $isJoinActivity */
        $isJoinActivity = UserActivity::whereUserId($user->id)->whereActivityId($thisActivity->id)->first();
        if($isJoinActivity && $isJoinActivity->status == 1)
            return response()->json(['level' => 'error','message' => '您已经报名过了']);

        if($isJoinActivity && $isJoinActivity->status == 2)
            return response()->json(['level' => 'error','message' => '您已经提交过申请了']);

        $joinNum = UserActivity::whereUserId($isBindPhone->user_id)->whereStatus(1)->count();
        if($thisActivity->max_join_num <= $joinNum)
            return response()->json(['level' => 'error','message' => '活动参与人数已满']);

        if(is_null($realName) || $realName == '')
            return response()->json(['level' => 'error','message' => '请填写姓名']);

        if(is_null($phone) || $phone == '')
            return response()->json(['level' => 'error','message' => '请填写手机号']);

        if(!preg_match("/^1[345789]{1}\d{9}$/",$phone))
            return response()->json(['level' => 'error','message' => '手机号格式不正确']);

        if(is_null($wechat) || $wechat == '')
            return response()->json(['level' => 'error','message' => '请填写微信号']);

        if($isGuest == 1){
            if($thisActivity->is_guest != 1)
                return response()->json(['level' => 'error','message' => '该活动不允许带客人']);

            if(!is_null($guestInfo) && is_array($guestInfo)){
                if(count($guestInfo) > 0){
                    foreach($guestInfo as $guest){
                        if(is_null($guest['name']) && $guest['name'] != '')
                            return response()->json(['level' => 'error','message' => '请填写客人的名字']);

                        if(is_null($guest['phone']) && $guest['phone'] != '')
                            return response()->json(['level' => 'error','message' => '请填写客人的手机号']);

                        if(is_null($guest['position']) && $guest['position'] != '')
                            return response()->json(['level' => 'error','message' => '请填写客人的职位']);
                    }
                }else{
                    return response()->json(['level' => 'error','message' => '请填写客人信息']);
                }
            }else{
                return response()->json(['level' => 'error','message' => '客人的数据格式不正确']);
            }
        }

        $buildJoinActivity = new UserActivity();
        $buildJoinActivity->user_id                                               = $user->id;
        $buildJoinActivity->activity_id                                           = $thisActivity->id;
        $buildJoinActivity->real_name                                             = $realName;
        $buildJoinActivity->phone                                                 = $phone;
        $buildJoinActivity->wechat                                                = $wechat;
        if($isGuest == 1) {
            $buildJoinActivity->is_with_people                            = 1;
        }else{
            $buildJoinActivity->is_with_people                            = 0;
        }
        $buildJoinActivity->pay_channel                                             = 1;
        $buildJoinActivity->status                                                  = 2;
        $buildJoinActivity->save();

        if($isGuest == 1){
            foreach($guestInfo as $guest) {
                $buildUserActivityGuest = new UserActivityGuest();
                $buildUserActivityGuest->user_id          = $user->id;
                $buildUserActivityGuest->activity_id      = $thisActivity->id;
                $buildUserActivityGuest->real_name        = $guest['name'];
                $buildUserActivityGuest->phone            = $guest['phone'];
                $buildUserActivityGuest->position         = $guest['position'];
                $buildUserActivityGuest->save();
            }
        }

        if($thisActivity->is_vip_free == 1){
            /** @var VipInfo $isVipUser */
            $isFree = VipInfo::whereUserId($user->id)->whereIsVip(1)->whereStatus(1)->where('end_time','>',date('Y-m-d H:i:s',time()))->first();
            if($isFree){
                $cost = 0.00;
            }else{
                $cost = $thisActivity->cost;
            }
        }else{
            $cost = $thisActivity->cost;
        }

        if($isGuest == 1){
            $cost = (float)$cost + (int)count($guestInfo) * (float)$thisActivity->guest_cost;
        }

        $newUserPayment = new UserPayment();
        $newUserPayment->user_id               = $user->id;
        $newUserPayment->vip_id                = $isVipUser->id;
        $newUserPayment->vip_card_number       = $isVipUser->vip_card_number;
        $newUserPayment->realname              = $isVipUser->realname;
        $newUserPayment->vip_rule_id           = $isVipUser->vip_rule_id;
        $newUserPayment->pay_id                = $isVipUser->pay_id;
        $newUserPayment->type                  = 'activity';
        $newUserPayment->activity_id           = $thisActivity->id;
        $newUserPayment->pay_channel           = 1;
        $newUserPayment->amount_receivable      = $cost;
        $newUserPayment->remarks                = '活动报名费用';
        if($cost <= 0){
            $newUserPayment->status             = 1;
            $newUserPayment->payment_time       = date("Y-m-d H:i:s",time());

            $buildJoinActivity->status = 1;
            $buildJoinActivity->save();
        }
        $newUserPayment->save();

        return response()->json(['level' => 'success','message' => '报名申请提交成功','data' => $buildJoinActivity]);
    }

//    /**
//     * 创建活动
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function buildActivity(Request $request){
//        /** @var User $user */
//        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//
//        $activeParty = ActiveParty::whereUserId($user->id)->whereStatus(1)->first();
//        if(!$activeParty)
//            return response()->json(['level' => 'error','message' => '您不是活动方，不能发布活动']);
//
//        $id                 =  !is_null( Input::get('id'))? Input::get('id'):0;
//        $name               =   Input::get('name');
//        $classifyId         =  !is_null( Input::get('classify_id')) ?  Input::get('classify_id') : 0;
//        $classifyTwo        =  !is_null( Input::get('classify_two')) ?  Input::get('classify_two') : 0;
//        $imgId              =  !is_null( Input::get('img_id')) ?  Input::get('img_id') : 0;
//        $desc               =   Input::get('desc');
//        $theme              =   Input::get('theme');
//        $province           =   Input::get('province');
//        $city               =   Input::get('city');
//        $area               =   Input::get('area');
//        $addressDetail      =   Input::get('address_detail');
//        $startTime          =   Input::get('start_time');
//        $endTime            =   Input::get('end_time');
//        $cost               =  !is_null( Input::get('cost')) ?  Input::get('cost') : 0.00;
//        $rePerson           =   Input::get('re_person');
//        $videoId            =  !is_null( Input::get('video_id')) ?  Input::get('video_id') : 0;
//        $infoImgIds         =   Input::get('info_img_ids');
//        $appDetail          =   Input::get('app_detail');
//
//        if(!is_array($infoImgIds))
//            return response()->json(['level' => 'error','message' => '活动介绍图片数据格式不正确']);
//
//        if(count($infoImgIds) > 5)
//            return response()->json(['level' => 'error','message' => '活动介绍图片只能上传5张哦']);
//
//        /** @var ActiveParty $thisActiveParty */
//        $thisActiveParty = ActiveParty::whereUserId($user->id)->whereStatus(1)->first();
//
//        /** @var Activity $projectInfo */
//        $newActivity = Activity::whereId($id)->first();
//        if(!$newActivity)
//            $newActivity = new Activity();
//
//        $newActivity->user_id                                    = $user->id;
//        if($thisActiveParty){
//            $newActivity->active_party_id                        = $thisActiveParty->id;
//        }
//        if(!is_null($name))$newActivity->name                    = $name;
//        if($classifyTwo != '' && $classifyTwo != 0){
//            $newActivity->classify_id                                = $classifyTwo;
//        }else{
//            $newActivity->classify_id                                = $classifyId;
//        }
//        $newActivity->img_id                                     = $imgId;
//        if(!is_null($desc))$newActivity->desc                    = $desc;
//        if(!is_null($theme))$newActivity->theme                  = $theme;
//        if(!is_null($province))$newActivity->province            = $province;
//        if(!is_null($city))$newActivity->city                    = $city;
//        if(!is_null($area))$newActivity->area                    = $area;
//        if(!is_null($addressDetail))$newActivity->address_detail = $addressDetail;
//        if(!is_null($startTime))$newActivity->start_time         = $startTime;
//        if(!is_null($endTime))$newActivity->end_time             = $endTime;
//        $newActivity->video_id                                   = $videoId;
//        $newActivity->cost                                       = $cost;
//        if(!is_null($rePerson))$newActivity->re_person           = $rePerson;
//        if(!is_null($appDetail))$newActivity->app_detail         = $appDetail;
//        $newActivity->status                                     = 1;
//        $newActivity->type                                       = 'app';
//        $newActivity->save();
//
//        if(count($infoImgIds) > 0){
//            foreach($infoImgIds as $infoImgId){
//                $newActivityImg = new ActivityImg();
//                $newActivityImg->activity_id = $newActivity->id;
//                $newActivityImg->img_id      = $infoImgId;
//                $newActivityImg->save();
//            }
//        }
//
//        return response()->json(['level' => 'success','message' => '设置成功','data' => $newActivity]);
//    }

//    /**
//     * 删除活动
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     * @throws \Exception
//     */
//    public function delActivity(Request $request){
//        /** @var User $user */
//        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);
//
//        $id = !is_null( Input::get('id')) ?  Input::get('id') : 0;
//
//        /** @var Activity $thatActivity */
//        $thatActivity = Activity::whereUserId($user->id)->whereId($id)->whereStatus(1)->first();
//        if(!$thatActivity)
//            return response()->json(['level' => 'error','message' => '该活动已下架']);
//
//        $activityJoin = JoinActivity::whereActivityId($thatActivity->id)->whereStatus(1)->get();
//        if(count($activityJoin) > 0)
//            return response()->json(['level' => 'error','message' => '该活动已有人参与，不可删除']);
//
//        $thatActivity->delete();
//
//        return response()->json(['level' => 'success','message' => '删除成功','data' => $thatActivity]);
//    }

//    /**
//     * 获取活动方列表
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function getActivePartyList(Request $request){
//        $type = !is_null( Input::get('type')) &&  Input::get('type') != '' ?  Input::get('type') : 'default';
//        $limit = !is_null( Input::get('limit')) ?  Input::get('limit') : 10;
//        $page = !is_null( Input::get('page')) ?  Input::get('page') : 0;
//
//        if($type == 'default'){
//            $activePartyList = ActiveParty::whereStatus(1)->orderBy('popularity','desc')->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
//        }elseif($type == 'popularity'){
//            $activePartyList = ActiveParty::whereStatus(1)->orderBy('popularity','desc')->orderBy('created_at','desc')->take(4)->get();
//        }else{
//            $activePartyList = ActiveParty::whereStatus(1)->orderBy('popularity','desc')->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
//        }
//
//        if(count($activePartyList) > 0){
//            foreach($activePartyList as $activeParty){
//                $activeParty->thumb_url = FileManager::getImgUrl($activeParty->thumb_id);
//            }
//        }
//
//        return response()->json(['level' => 'success','message' => '获取成功','data' => $activePartyList]);
//    }
//
//    /**
//     * 获取活动方详情
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function getActivePartyDetail(Request $request){
//        $activePartyId = !is_null( Input::get('active_party_id')) ?  Input::get('active_party_id') : 0;
//
//        /** @var ActiveParty $activePartyDetail */
//        $activePartyDetail = ActiveParty::whereId($activePartyId)->whereStatus(1)->first();
//        if($activePartyDetail){
//            $activePartyDetail->logo_url = FileManager::getImgUrl($activePartyDetail->logo_id);
//        }
//
//        return response()->json(['level' => 'success','message' => '获取成功','data' => $activePartyDetail]);
//    }
}
